import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation as useRouteLocation } from 'react-router-dom';
import { useLocation } from '../../context/LocationContext';
import { Modal } from 'antd-mobile';

// 定义类型
interface PickupPoint {
  name: string;
  distance: number;
  address: string;
  image: string;
}

interface CityData {
  current: PickupPoint;
  nearby: PickupPoint[];
}

interface PickupDataType {
  [key: string]: CityData;
}

// 生成城市的默认提货点数据
const generateDefaultPickupData = (cityName: string): CityData => {
  return {
    current: {
      name: `${cityName}万达广场店`,
      distance: 83,
      address: `${cityName}市中心万达广场`,
      image: "",
    },
    nearby: [
      {
        name: `${cityName}大悦城店`,
        distance: 120,
        address: `${cityName}市中心大悦城`,
        image: "",
      },
      {
        name: `${cityName}龙湖天街店`,
        distance: 180,
        address: `${cityName}市中心龙湖天街`,
        image: "",
      },
      {
        name: `${cityName}环球中心店`,
        distance: 250,
        address: `${cityName}市中心环球中心`,
        image: "",
      },
    ]
  };
};

// 基础城市数据
const basePickupData: PickupDataType = {
  "重庆": {
    current: {
      name: "重庆万达广场店",
      distance: 83,
      address: "重庆市渝中区解放碑步行街1号",
      image: "",
    },
    nearby: [
      {
        name: "重庆龙湖时代天街店",
        distance: 120,
        address: "重庆市渝中区长江二路174号",
        image: "",
      },
      {
        name: "重庆观音桥大融城店",
        distance: 200,
        address: "重庆市江北区建新北路38号",
        image: "",
      },
      {
        name: "重庆大坪龙湖店",
        distance: 300,
        address: "重庆市渝中区大坪正街19号",
        image: "",
      },
    ]
  },
  "北京": {
    current: {
      name: "北京万达广场店",
      distance: 83,
      address: "北京市石景山区石景山路乙18号-1栋A102",
      image: "",
    },
    nearby: [
      {
        name: "北京朝阳大悦城店",
        distance: 120,
        address: "北京市朝阳区朝阳北路101号",
        image: "",
      },
      {
        name: "北京西单大悦城店",
        distance: 180,
        address: "北京市西城区西单北大街131号",
        image: "",
      },
      {
        name: "北京三里屯太古里店",
        distance: 250,
        address: "北京市朝阳区三里屯路19号",
        image: "",
      },
    ]
  },
  "上海": {
    current: {
      name: "上海环球港店",
      distance: 83,
      address: "上海市普陀区中山北路3300号",
      image: "",
    },
    nearby: [
      {
        name: "上海正大广场店",
        distance: 220,
        address: "上海市浦东新区陆家嘴西路168号",
        image: "",
      },
      {
        name: "上海五角场万达店",
        distance: 150,
        address: "上海市杨浦区淞沪路77号",
        image: "",
      },
      {
        name: "上海静安大悦城店",
        distance: 300,
        address: "上海市静安区西藏北路166号",
        image: "",
      },
    ]
  }
};

// 创建代理对象来处理未定义的城市
const pickupData: PickupDataType = new Proxy(basePickupData, {
  get: (target, prop) => {
    if (prop in target) {
      return target[prop as string];
    }
    // 如果城市不存在，返回默认数据
    return generateDefaultPickupData(prop as string);
  }
});

export default function Zhi() {
  const navigate = useNavigate();
  const routeLocation = useRouteLocation();
  const { setLocation } = useLocation();
  const [city, setCity] = useState("重庆");
  const [selectedPickup, setSelectedPickup] = useState<PickupPoint | null>(null);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [currentPickup, setCurrentPickup] = useState<PickupPoint>(pickupData["重庆"].current);
  const [nearbyPickups, setNearbyPickups] = useState<PickupPoint[]>(pickupData["重庆"].nearby);
  const [searchText, setSearchText] = useState('');
  const [filteredNearbyPickups, setFilteredNearbyPickups] = useState<PickupPoint[]>(pickupData["重庆"].nearby);

  // 处理城市变化，更新当前自提点和附近自提点
  useEffect(() => {
    if (city) {
      const cityData = pickupData[city];
      setCurrentPickup(cityData.current);
      setNearbyPickups(cityData.nearby);
      setFilteredNearbyPickups(cityData.nearby);
      setSearchText('');
      setLocation(cityData.current.name); // Update global location when city changes
    }
  }, [city, setLocation]);

  // 接收从Location页面传来的城市信息
  useEffect(() => {
    if (routeLocation.state?.selectedCity) {
      setCity(routeLocation.state.selectedCity);
    }
    // 处理从修改定位页面返回的新地址
    if (routeLocation.state?.newLocation) {
      // 这里可以添加处理新地址的逻辑
      console.log('New location:', routeLocation.state.newLocation);
    }
  }, [routeLocation.state]);

  // 处理搜索
  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    const searchValue = e.target.value;
    setSearchText(searchValue);
    
    if (!searchValue.trim()) {
      setFilteredNearbyPickups(nearbyPickups);
      return;
    }

    const searchLower = searchValue.toLowerCase();
    const filtered = nearbyPickups.filter(point => 
      point.name.toLowerCase().includes(searchLower) ||
      point.address.toLowerCase().includes(searchLower)
    );
    setFilteredNearbyPickups(filtered);
  };

  const handleSelect = (pickup: PickupPoint) => {
    setSelectedPickup(pickup);
    setShowConfirmModal(true);
  };

  const handleConfirm = () => {
    if (selectedPickup) {
      setLocation(selectedPickup.name);
      setCurrentPickup(selectedPickup);
      setShowConfirmModal(false);
      navigate('/home', { replace: true }); // 使用 replace 模式导航到首页
    }
  };

  const handleCancel = () => {
    setSelectedPickup(null);
    setShowConfirmModal(false);
  };

  // 处理修改定位
  const handleLocationChange = () => {
    navigate('/xiugaidingwei');
  };

  return (
    <div style={{ background: '#fff', minHeight: '100vh', fontFamily: 'sans-serif' }}>
      <div style={{ padding: '16px', borderBottom: '1px solid #eee', fontWeight: 'bold', fontSize: 18, textAlign: 'center', position: 'relative' }}>
        <button
          onClick={() => navigate('/home')}
          style={{ position: 'absolute', left: 8, top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', fontSize: 20, cursor: 'pointer', color: '#333' }}
          aria-label="返回"
        >←</button>
        选择提货点
      </div>
      <div style={{ display: 'flex', alignItems: 'center', padding: '16px' }}>
        <button 
          onClick={() => navigate('/location')}
          style={{ 
            fontSize: 16, 
            marginRight: 8, 
            border: '1px solid #eee',
            borderRadius: 4,
            padding: '6px 12px',
            background: '#fff',
            display: 'flex',
            alignItems: 'center',
            cursor: 'pointer'
          }}
        >
          {city}
          <span style={{ marginLeft: 4, fontSize: 12, color: '#666' }}>▼</span>
        </button>
        <input 
          value={searchText}
          onChange={handleSearch}
          placeholder="请输入自提点名称或地址" 
          style={{ flex: 1, border: '1px solid #eee', borderRadius: 4, padding: 6 }} 
        />
      </div>
      <div style={{ padding: '0 16px', color: '#888', fontSize: 15, marginBottom: 8 }}>
        <span role="img" aria-label="定位">📍</span> {currentPickup.name}
        <span
          style={{ float: 'right', color: '#007aff', cursor: 'pointer' }}
          onClick={handleLocationChange}
        >
          修改定位
        </span>
      </div>
      <div style={{ background: '#fafafa', padding: '12px 16px 0 16px', fontWeight: 'bold', fontSize: 16 }}>当前自提点</div>
      <div style={{ display: 'flex', alignItems: 'center', padding: '12px 16px', borderBottom: '1px solid #eee' }}>
        <div style={{ width: 48, height: 48, background: '#f0f0f0', borderRadius: 8, marginRight: 12, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <span role="img" aria-label="图片" style={{ fontSize: 28, color: '#ccc' }}>🖼️</span>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 'bold', fontSize: 16 }}>{currentPickup.name}</div>
          <div style={{ color: 'red', fontSize: 14 }}>距离{currentPickup.distance}m</div>
          <div style={{ color: '#888', fontSize: 13 }}>{currentPickup.address}</div>
        </div>
      </div>
      <div style={{ background: '#fafafa', padding: '12px 16px 0 16px', fontWeight: 'bold', fontSize: 16 }}>
        {filteredNearbyPickups.length === 0 ? '未找到相关自提点' : '附近自提点'}
      </div>
      {filteredNearbyPickups.map((item, idx) => (
        <div key={idx} style={{ display: 'flex', alignItems: 'center', padding: '12px 16px', borderBottom: '1px solid #eee' }}>
          <div style={{ width: 48, height: 48, background: '#f0f0f0', borderRadius: 8, marginRight: 12, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <span role="img" aria-label="图片" style={{ fontSize: 28, color: '#ccc' }}>🖼️</span>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 'bold', fontSize: 16 }}>{item.name}</div>
            <div style={{ color: 'red', fontSize: 14 }}>距离{item.distance}m</div>
            <div style={{ color: '#888', fontSize: 13 }}>{item.address}</div>
          </div>
          <button style={{ background: '#ff2d55', color: '#fff', border: 'none', borderRadius: 16, padding: '6px 18px', fontSize: 15, cursor: 'pointer' }} onClick={() => handleSelect(item)}>选择</button>
        </div>
      ))}
      <Modal
        visible={showConfirmModal}
        content={
          selectedPickup ? (
            <div style={{ padding: '16px 0' }}>
              <div style={{ marginBottom: '12px', textAlign: 'center', fontSize: '16px', fontWeight: 'bold' }}>
                是否确认修改自提点？
              </div>
              <div style={{ background: '#f5f5f5', padding: '12px', borderRadius: '8px' }}>
                <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>{selectedPickup.name}</div>
                <div style={{ color: '#ff4d4f', fontSize: '14px', marginBottom: '4px' }}>
                  距离约 {selectedPickup.distance}m
                </div>
                <div style={{ color: '#666', fontSize: '14px' }}>{selectedPickup.address}</div>
              </div>
            </div>
          ) : '是否确认修改自提点？'
        }
        closeOnAction
        onClose={() => setShowConfirmModal(false)}
        actions={[
          {
            key: 'cancel',
            text: '取消',
            onClick: handleCancel,
            style: { color: '#999' }
          },
          {
            key: 'confirm',
            text: '确认',
            onClick: handleConfirm,
            style: { color: '#ff4d4f' }
          }
        ]}
      />
    </div>
  );
}